package com.xca.gsondemo.views;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xca.gsondemo.R;
import com.xca.gsondemo.adapter.HotAdapter;
import com.xca.gsondemo.entity.Hot;
import com.xca.gsondemo.entity.Olympic;
import com.xca.gsondemo.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

public class HotFragment extends Fragment {
    private View hotFragment ;
    private ListView listView ;
    private List<Hot> mList = new ArrayList<>();
    private HotAdapter adapter ;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        hotFragment = inflater.inflate(R.layout.hot , container , false);
        listView = hotFragment.findViewById(R.id.h_list);
        testJsonParser();
        adapter = new HotAdapter(getContext() , R.layout.hot_item , mList);
        listView.setAdapter(adapter);
        return hotFragment ;
    }


    //在"result"键外没有其他键，可直接调用
    private void testJsonParser() {
        String jsonStr = getJson("hotsearch.json");
        JsonObject jo = JsonParser.parseString(jsonStr).getAsJsonObject();
        JsonArray array = jo.get("result").getAsJsonArray();
        for (JsonElement jsonElement : array) {
            Hot hot = new Hot();
            hot.setIndex(jsonElement.getAsJsonObject().get("index").getAsString());
            hot.setTitle(jsonElement.getAsJsonObject().get("title").getAsString());
            hot.setHotValue(jsonElement.getAsJsonObject().get("hotValue").getAsString());
            hot.setLink(jsonElement.getAsJsonObject().get("link").getAsString());
            mList.add(hot);
            Log.d("asdf", " ==name== " + hot.getHotValue());
        }
    }

    private String getJson(String name) {
        if (getActivity() == null) return null; // 防止空指针异常
        String json = JsonUtils.getJsonFromAssets(getActivity(), name);
        Log.d("获取所有", "getJson: " + json);
        return json;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hotFragment = null ;
    }
}
